use serde::{Deserialize, Serialize};
use std::fs;

#[derive(Debug, Serialize, Deserialize,Clone)]
pub struct ConfigModel {
    pub media_in_port : String,
    pub media_out_port : String,
}

impl ConfigModel {
    //默认值
    fn default() -> Self {
        ConfigModel {
            media_in_port:"8888".to_owned(),
            media_out_port:"6666".to_owned(),
        }
    }
    pub fn get_config(path:&str)->(String,String){
        let config=ConfigModel::read(path).unwrap();
        (config.media_in_port,config.media_out_port)
    }
    //读取配置文件
    pub fn read(path:&str) -> Result<ConfigModel, std::io::Error> {
        let bts = match fs::read(path) {
            Ok(bts) => bts,
            Err(_) => {
                let config = ConfigModel::default();
                config.write(path.to_string())?;
                return Ok(config);
            }
        };
        let str = std::str::from_utf8(&bts).unwrap();
        let config : ConfigModel = serde_xml_rs::from_str(str).unwrap();
        Ok(config)
    }

    fn write(&self, path:String) -> Result<(), std::io::Error> {
        let str = serde_xml_rs::to_string(self).unwrap();
        fs::write(path, str)?;
        Ok(())
    }
}


